import React, { useEffect, useState, Key } from 'react';
import {
  Button,
  Card,
  Form,
  Input,
  Space,
  Table,
  Tag,
  Tooltip,
  message,
  Modal,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';

import {
  reqHospitalSet,
  reqDelOneHospitalSet,
  reqDelAll,
} from '@api/hospitalSet';
import {
  IhospitalSetList,
  IhospitalSetItem,
} from '@api/hospitalSet/modal/hospitalsetType';
import { useNavigate } from 'react-router-dom';
//引入批量删除弹框
const { confirm } = Modal;
//定义变量，当用户点击查询按钮才进行查询
let flag = false;
export default function Index() {
  const [list, setList] = useState<IhospitalSetList>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(2);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  //定义模态框状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // const [id, setId] = useState('')

  //定义批量删除默认的状态
  const [ids, setIds] = useState<Key[]>([]);
  useEffect(() => {
    fetch(page, pageSize);
  }, []);
  async function fetch(page: number, pageSize: number) {
    //获取form实例，然后绑定，用getFieldsValue获取数据
    const { hosname, hoscode } = form.getFieldsValue();
    let result;
    if (flag) {
      result = await reqHospitalSet(page, pageSize, hosname, hoscode);
    } else {
      result = await reqHospitalSet(page, pageSize);
    }

    setList(result.records);
    setTotal(result.total);
  }
  //表单提交事件
  const onFinish = (values: any) => {
    //点了查询才为true
    flag = true;
    fetch(page, pageSize);
    setPage(1);
  };
  // //清空数据
  const clearFrom = () => {
    flag = false;
    //清空表单
    form.setFieldsValue({ hosname: undefined, hoscode: undefined });
    setPage(1);
    fetch(page, pageSize);
  };

  //清除弹框
  const handleOk = (id: string) => {
    return async () => {
      await reqDelOneHospitalSet(id);
      message.success('删除成功');
      //页面重新渲染
      fetch(page, pageSize);
      setIsModalOpen(false);
    };
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //批量清除
  const DelAllSelect =() =>{
    confirm({
      title: '确定删除吗?',
      icon: <ExclamationCircleOutlined />,
       async onOk() {
        //点击确定按钮，发送请求，重新渲染页面
       await reqDelAll(ids)
       message.success('删除成功')
       fetch(page,pageSize)
       setIds([])
      },
    
    });
  }

  const columns: ColumnsType<IhospitalSetItem> = [
    {
      title: '序号',
      //   dataIndex: 'name',
      // key: 'name',
      render: (_, record, index) => index + 1,
      align: 'center',
      width: 80,
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
      // key: 'age',
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
      // key: 'address',
    },
    {
      title: 'api基础路径',
      //   key: 'tags',
      dataIndex: 'apiUrl',
    },
    {
      title: '签名',
      dataIndex: 'signKey',
    },
    {
      title: '联系人名称',
      dataIndex: 'contactsName',
    },
    {
      title: '联系人电话',
      dataIndex: 'contactsPhone',
    },
    {
      title: '操作',
      //   key: 'age',
      render: (_) => {
        return (
          <Space>
            <Tooltip title="修改医院">
              <Button
                type="primary"
                icon={<EditOutlined />}
                onClick={() => {
                  navigate(`/syt/hospital/hospitalSet/edit/${_.id}`);
                }}
              ></Button>
            </Tooltip>
            <Tooltip title="删除医院">
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                onClick={() => {
                  setIsModalOpen(true);
                  // setId(_.id);
                }}
              ></Button>
            </Tooltip>
            <Modal
              title="Basic Modal"
              visible={isModalOpen}
              // open={isModalOpen}
              onOk={handleOk(_.id)}
              onCancel={handleCancel}
            >
              <p>确定删除吗？</p>
            </Modal>
          </Space>
        );
      },
      width: 80,
      fixed: 'right',
    },
  ];
  return (
    <Card>
      <Form layout="inline" form={form} onFinish={onFinish}>
        <Form.Item name="hosname">
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号"></Input>
        </Form.Item>
        <Form.Item></Form.Item>
        <Form.Item>
          <Space size="small">
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
              查询
            </Button>
            <Button onClick={clearFrom}>清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <Space className="gap">
        <Button
          type="primary"
          onClick={() => {
            navigate('/syt/hospital/hospitalSet/add');
          }}
        >
          添加
        </Button>
        <Button type="primary" danger disabled={!ids.length} onClick={DelAllSelect}>
          批量删除
        </Button>
      </Space>
      <Table
        rowKey={'id'}
        columns={columns}
        dataSource={list}
        className="gap"
        bordered
        rowSelection={{
          onChange(selectedRowKeys: Key[], selectedRows: IhospitalSetList) {
            setIds(selectedRowKeys);
          },
        }}
        scroll={{ x: 1500 }}
        //分页器
        pagination={{
          current: page,
          total,
          pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: [2, 5, 10],
          showTotal: (total) => {
            return `总共${total}条`;
          },
          //点击分页器获取最新数据
          onChange: (page, pageSize) => {
            setPage(page);
            setPageSize(pageSize);
            fetch(page, pageSize);
          },
        }}
      />
    </Card>
  );
}
